//
//  PostViewController.m
//  AIM
//
//  Created by user10 on 2017/5/18.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "PostViewController.h"
#import <Masonry.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import "UIImage+Extension.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "AimTapGestureRecognizer.h"
#import "DemoViewController.h"
#import "RecordAudio.h"
#import "DeviceInfo.h"
#import "NetWorkTools.h"

#define BIG_IMG_WIDTH  [UIScreen mainScreen].bounds.size.width
#define BIG_IMG_HEIGHT [UIScreen mainScreen].bounds.size.width * 16 / 9
@interface PostViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,UITextFieldDelegate,DemoViewControllerDelegate,UITextViewDelegate,UIScrollViewDelegate,AVPlayerViewControllerDelegate>{
    UIScrollView *background;
    UIImageView *imageView;
}


@property (nonatomic, strong)RecordAudio *recordAudio;

@property (nonatomic, strong) AVPlayerViewController  *avPlayer;

@end


@implementation PostViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    //创建子控件
    [self createSubViews];
    //布局子控件
    [self layoutSubViews];
    _dataName =[NSString string];
    _dataType =[NSString string];
    _dataString =[NSString string];
    _voiceData = [NSData data];
    _productTextFiled.delegate = self;
    _recordAudio = [[RecordAudio alloc]init];
    
    [_titleTextFiled addTarget:self action:@selector(limit:) forControlEvents:UIControlEventEditingChanged];
}
//限制文本框的输入内容和文本的长度
- (void)limit:(UITextField *)textField{
    //限制文本的输入长度不得大于10个字符长度
    if (textField.text.length >= 40){
        //截取文本字符长度为10的内容
        textField.text = [textField.text substringToIndex:40];
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"入力した文字数は制限を超えている" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
        [alert show];
    }
}
- (void)createSubViews{
    UIScrollView *scrollV = [[UIScrollView alloc]init];
    scrollV.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    [self.view addSubview:scrollV];
    _scrollV = scrollV;
    
    //底部SHARE按钮
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareBtn setTitle:@"SHARE" forState:UIControlStateNormal];
    shareBtn.backgroundColor = [UIColor purpleColor];
    shareBtn.layer.cornerRadius = 5;
    shareBtn.titleLabel.textColor = [UIColor whiteColor];
    [shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareBtn];
    _shareBtn = shareBtn;
    
    
    //标题输入框
    UITextField *titleTextFiled = [[UITextField alloc]init];
    titleTextFiled.placeholder = @"Enter the title";
    titleTextFiled.borderStyle = UITextBorderStyleRoundedRect;
    titleTextFiled.returnKeyType = UIReturnKeyDone;
    titleTextFiled.delegate = self;
    [scrollV addSubview:titleTextFiled];
    _titleTextFiled = titleTextFiled;
    UIToolbar *bar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width,44)];

    UIBarButtonItem * button1 =[[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem * button2 = [[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    //定义完成按钮
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone  target:self action:@selector(finish)];
    
    //在toolBar上加上这些按钮
    NSArray * buttonsArray = [NSArray arrayWithObjects:button1,button2,doneButton,nil];
    [bar setItems:buttonsArray];
    
    _titleTextFiled.inputAccessoryView = bar;
    
    //详情输入框
    UITextView *detailTextFiled = [[UITextView alloc]init];
    detailTextFiled.delegate = self;
    detailTextFiled.layer.cornerRadius = 3;
    detailTextFiled.font = [UIFont systemFontOfSize:17];
    [scrollV addSubview:detailTextFiled];
    _detailTextFiled = detailTextFiled;
    _detailTextFiled.inputAccessoryView = bar;
    
    //TextView 占位Lable
    UILabel *placeholderL = [[UILabel alloc]init];
    placeholderL.text = @"Share your story here...";
    placeholderL.textAlignment = NSTextAlignmentLeft;
    placeholderL.textColor = [UIColor lightGrayColor];
    _placeholderL = placeholderL;
    [scrollV addSubview:_placeholderL];
    
    //productLabel
    UILabel * productL = [[UILabel alloc]init];
    productL.text = @"PRODUCT NO.";
    productL.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:productL];
    _productL = productL;
    
    //product 输入框
    UITextField *productTextFiled = [[UITextField alloc]init];
    productTextFiled.placeholder = @"Comma separated";
    productTextFiled.borderStyle = UITextBorderStyleRoundedRect;
    productTextFiled.returnKeyType = UIReturnKeySend;
    [scrollV addSubview:productTextFiled];
    _productTextFiled = productTextFiled;
    _productTextFiled.inputAccessoryView = bar;
    
    //文件选择按钮
    UIButton *fileBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [fileBtn setTitle:@"File" forState:UIControlStateNormal];
    fileBtn.backgroundColor = [UIColor blueColor];
    fileBtn.layer.cornerRadius = 5;
    [scrollV addSubview:fileBtn];
    [fileBtn addTarget:self action:@selector(alertClick) forControlEvents:UIControlEventTouchUpInside];
    _fileBtn = fileBtn;
    
    //语音按钮
    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceBtn setBackgroundImage:[UIImage imageNamed:@"postcomment_menu_voice"] forState:UIControlStateNormal];
    [voiceBtn addTarget:self action:@selector(clickVoice) forControlEvents:UIControlEventTouchUpInside];
    [scrollV addSubview:voiceBtn];
    _voiceBtn = voiceBtn;
    
    //图片
    UIImageView *image = [[UIImageView alloc]init];
    [scrollV addSubview:image];
    _image = image;
    
    //语音按钮
    UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [delBtn setBackgroundImage:[UIImage imageNamed:@"post_cross"] forState:UIControlStateNormal];
    [scrollV addSubview:delBtn];
    delBtn.hidden = YES;
    [delBtn addTarget:self action:@selector(del) forControlEvents:UIControlEventTouchUpInside];
    _delBtn = delBtn;
    
}

- (void)layoutSubViews {
    //scrollView布局
    [_scrollV mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat height = [UIScreen mainScreen].bounds.size.height - 133;
        //尺寸约束
        make.size.mas_equalTo(CGSizeMake([UIScreen mainScreen].bounds.size.width, height));
        //位置约束
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.top.mas_equalTo(self.view.mas_top).offset(5);
    }];
    //分享按钮布局
    [_shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(90,44));
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(_scrollV.mas_bottom);
    }];
    
    //title输入框布局
    [_titleTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 10;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_scrollV.mas_left).offset(5);
        make.top.mas_equalTo(_scrollV.mas_top).offset(0);
    }];
    //详情输入框布局
    [_detailTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 10;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(260);
        make.left.mas_equalTo(_titleTextFiled.mas_left).offset(0);
        make.top.mas_equalTo(_titleTextFiled.mas_bottom).offset(5);
    }];
    //占位label布局
    [_placeholderL mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 10;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(35);
        make.left.mas_equalTo(_detailTextFiled.mas_left).offset(5);
        make.top.mas_equalTo(_detailTextFiled.mas_top).offset(0);
    }];
    //lable布局
    [_productL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_detailTextFiled.mas_left).offset(0);
        make.top.mas_equalTo(_detailTextFiled.mas_bottom).offset(5);
    }];
    //productNo布局
    [_productTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 10;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_productL.mas_left).offset(0);
        make.top.mas_equalTo(_productL.mas_bottom).offset(5);
    }];
    //文件选择按钮布局
    [_fileBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width * 0.25;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_productTextFiled.mas_left).offset(0);
        make.top.mas_equalTo(_productTextFiled.mas_bottom).offset(5);
    }];
    
    //录音按钮布局
    [_voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(30);
        make.right.mas_equalTo(_productTextFiled.mas_right);
        make.top.mas_equalTo(_fileBtn.mas_top);
    }];
    //图片位置的布局
    [_image mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width * 0.33;
        CGFloat height = width * 4 / 3;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(height);
        make.top.mas_equalTo(_fileBtn.mas_bottom).offset(5);
        make.centerX.mas_equalTo(_scrollV.mas_centerX);
    }];
    
    //删除按钮布局
    [_delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_image.mas_right).offset(5);
        make.top.mas_equalTo(_image.mas_top);
    }];

    _scrollV.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 650);
}
- (void)alertClick{
    
    NSLog(@"111");
    //alert弹层
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    //照片库
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"Photo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"照片库");
        UIImagePickerController *pick=[[UIImagePickerController alloc]init];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pick.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            pick.allowsEditing=true;
            pick.delegate=self;
            [self presentViewController:pick animated:true completion:nil];
        }
        else
        {
            NSLog(@"相册不可用");
        }
    }];
    
    //视频库
    UIAlertAction *video = [UIAlertAction actionWithTitle:@"Video" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"视频库");
        UIImagePickerController *pick=[[UIImagePickerController alloc]init];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pick.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            pick.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];
            pick.allowsEditing=true;
            pick.delegate=self;
            [self presentViewController:pick animated:true completion:nil];
        }
        else
        {
            NSLog(@"相册不可用");
        }
    }];
    //拍摄照片
    UIAlertAction *takephoto  = [UIAlertAction actionWithTitle:@"Take a picture" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIImagePickerController *pick=[[UIImagePickerController alloc]init];
            pick.sourceType=UIImagePickerControllerSourceTypeCamera;//设置 pick 的类型为相机
            pick.allowsEditing=true;//设置是否可以编辑相片涂鸦
            pick.delegate=self;
            [self presentViewController:pick animated:true completion:nil];
        }
        else
        {
            NSLog(@"相机不可用");
        }
        NSLog(@"拍摄照片");
    }];
    
    //拍摄视频
    UIAlertAction *takeVideo  = [UIAlertAction actionWithTitle:@"Shoot a video" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"拍摄视频");
        _dataName = [self getNameBaseCurrentTime:@".mov"];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSArray * mediaTypes =[UIImagePickerController  availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            UIImagePickerController *pick=[[UIImagePickerController alloc]init];
            pick.sourceType = UIImagePickerControllerSourceTypeCamera;//设置 pick 的类型为相机
            pick.mediaTypes = @[mediaTypes[1]];
            pick.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
            pick.allowsEditing=true;//设置是否可以编辑相片涂鸦
            pick.delegate=self;
            [self presentViewController:pick animated:true completion:nil];
        }
        else
        {
            NSLog(@"相机不可用");
        }
        NSLog(@"拍摄照片");
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:photo];
    [alertController addAction:video];
    [alertController addAction:takephoto];
    [alertController addAction:takeVideo];
    if([DeviceInfo deviceIsPhone]){
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
        UIPopoverPresentationController *popPresenter = [alertController
                                                         popoverPresentationController];
        
        popPresenter.sourceView = _fileBtn; // 这就是挂靠的对象
        popPresenter.sourceRect = _fileBtn.bounds;
        popPresenter.permittedArrowDirections = UIPopoverArrowDirectionDown;
        [self presentViewController:alertController animated:YES completion: nil];
    }
}
- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text length] > 1000) {
        textView.text = [textView.text substringWithRange:NSMakeRange(0, 1000)];
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"入力した文字数は制限を超えている" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
        [alert show];
        [textView.undoManager removeAllActions];
        [textView becomeFirstResponder];
        return;
    }
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.titleTextFiled ) {
        if (textField.text.length > 40) {
            textField.text = [textField.text substringToIndex:40];
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"入力した文字数は制限を超えている" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}
- (void)finish{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (![text isEqualToString:@""]) {
        _placeholderL.hidden = YES;
    }
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
        _placeholderL.hidden = NO;
    }
    return YES;
}

- (void)del{
    _image.image = nil;
    _delBtn.hidden = YES;
    _voiceData = NULL;
    _dataString = @"";
    _dataName = @"";
    _dataType = @"";
}

- (void)clickVoice{
    DemoViewController *voiceVc = [[DemoViewController alloc]init];
    voiceVc.delegate = self;
    voiceVc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    
    voiceVc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:voiceVc animated:YES completion:nil];
}

- (void)preparePost:(NSData *)data{
    _delBtn.hidden = NO;
    [_image setImage:[UIImage imageNamed:@"play_l6"]];
    _dataType = @"AUDIO";
    _voiceData = data;
    
    NSString *base64String = [data base64EncodedStringWithOptions:0];
    _dataString = base64String;
    _dataName = [self getNameBaseCurrentTime:@".mp3"];
    _image.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapVoice)];
    [_image addGestureRecognizer:tapGesture];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type=[info objectForKey:UIImagePickerControllerMediaType];
    
    NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    // define the block to call when we get the asset based on the url (below)
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
    {
        if ([type isEqualToString:@"public.image"])
        {
//            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
//                
//                _dataName = [self getNameBaseCurrentTime:@".png"];
//                
//            } else {
//                
//                _dataName = [self getNameBaseCurrentTime:@"jpg"];
//                
//            }
            _dataName = [self getNameBaseCurrentTime:@".png"];
        }else{
        ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
        _dataName = [imageRep filename];
            if (_dataName == nil) {
                
                _dataName = [self getNameBaseCurrentTime:@".mov"];
                
            }
        }
    };
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
    
    //判断选择的是否是图片,这个 public.image和public.movie是固定的字段.
    if ([type isEqualToString:@"public.image"])
    {
        //设置dataType类型
        _dataType = @"IMAGE";
        
        //这样就已经实现了设置图片的功能
        UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
        
        if (picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
            UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
        }
//        NSData *imageData = UIImagePNGRepresentation(image);
        NSData *imageData = [UIImage compressWithOrgImg:image];
        NSString *base64String = [imageData base64EncodedStringWithOptions:0];
        _dataString = base64String;
        [_image setImage:image];
        
        //允许用户交互
        _image.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapActions)];
        [_image addGestureRecognizer:tapGesture];
        if (_image.image != nil) {
            _delBtn.hidden = NO;
        }
    }
    //判断选择的是否是视频
    if ([type isEqualToString:@"public.movie"]) {
        //如果是视频资源
        NSURL *sourceURL = info[UIImagePickerControllerMediaURL];
//        [self compressVideo:sourceURL];
        _videoUrl = [sourceURL absoluteString];
        NSData *data = [NSData dataWithContentsOfURL:sourceURL];
        
        NSString *base64String = [data base64EncodedStringWithOptions:0];
        
        _dataName = [self getNameBaseCurrentTime:@".mov"];
        _dataType = @"VIDEO";
        _dataString = base64String;
        _image.image = [self thumbnailImageForVideo:sourceURL atTime:1];
        //允许用户交互
        _image.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playVideos)];
        [_image addGestureRecognizer:tapGesture];
        if (_image.image != nil) {
            _delBtn.hidden = NO;
        }
//        self.videoUrl = sourceURL;
//        NSURL *newVideoUrl ; //一般.mp4
        NSLog(@"%@",sourceURL);
        
        [picker dismissViewControllerAnimated:YES completion:^{}];
    }
    [picker dismissViewControllerAnimated:false completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"取消");
    [picker dismissViewControllerAnimated:false completion:nil];
}
//播放音频
- (void)tapVoice{
    
    [_recordAudio play:_voiceData];
}
//播放视频
- (void)playVideos
{
    
    NSString *url = _videoUrl;
    
    NSURL * videoURL = [NSURL URLWithString:url];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
    if (error) {
        NSLog(@"error = %@",[error description]);
    }
    
    _avPlayer = [[AVPlayerViewController alloc] init];
    //    _avPlayer.player = [[AVPlayer alloc] initWithURL:videoURL];
    _avPlayer.delegate = self;
    _avPlayer.videoGravity = AVLayerVideoGravityResizeAspect;
    AVAsset *asset = [AVAsset assetWithURL:videoURL];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    _avPlayer.player = player;
    [self presentViewController:_avPlayer animated:YES completion:^{
        [_avPlayer.player play];
    }];

    
}

- (BOOL)playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart:(AVPlayerViewController *)playerViewController
{
    //表示最小化后，dismiss掉原来视图的的layer
    return YES;
}

- (void)playerViewController:(AVPlayerViewController *)playerViewController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL))completionHandler
{
    //恢复原来的视图 重新present
    [self presentViewController:playerViewController animated:YES completion:^{
        completionHandler(YES);
    }];
}

//点击图片后的方法
- (void)tapActions{
    //创建一个黑色背景
    //初始化一个用来当做背景的View。
    UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    background = bgView;
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
    [self.view addSubview:bgView];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        //创建显示图像的视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BIG_IMG_WIDTH, BIG_IMG_HEIGHT)];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imageView = imgView;
        //要显示的图片，即要放大的图片
        [imgView setImage:_image.image];
        [bgView addSubview:imgView];
        CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        bgView.contentSize = size;
        
        //设置代理scrollview的代理对象
        bgView.delegate=self;
        //设置最大伸缩比例
        bgView.maximumZoomScale=2.0;
        //设置最小伸缩比例
        bgView.minimumZoomScale=1;
        
        imgView.userInteractionEnabled = YES;
        //添加点击手势（即点击图片后退出全屏）
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
        [imgView addGestureRecognizer:tapGesture];
        
        [self shakeToShow:bgView];//放大过程中的动画
        
    } else {
        //创建显示图像的视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BIG_IMG_WIDTH , [UIScreen mainScreen].bounds.size.height)];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imageView = imgView;
        //要显示的图片，即要放大的图片
        [imgView setImage:_image.image];
        [bgView addSubview:imgView];
        
        CGSize size = CGSizeMake(BIG_IMG_WIDTH  , [UIScreen mainScreen].bounds.size.height );
        bgView.contentSize = size;
        
        //设置代理scrollview的代理对象
        bgView.delegate=self;
        //设置最大伸缩比例
        bgView.maximumZoomScale=2.0;
        //设置最小伸缩比例
        bgView.minimumZoomScale=1;
        
        imgView.userInteractionEnabled = YES;
        //添加点击手势（即点击图片后退出全屏）
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
        [imgView addGestureRecognizer:tapGesture];
        
        [self shakeToShow:bgView];//放大过程中的动画
        
    }
    
}
//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageView;
}
-(void)closeView{
    [background removeFromSuperview];
}

//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.2;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

- (void)share{
    if ((_titleTextFiled.text.length == 0) && (_detailTextFiled.text.length == 0) && (_productTextFiled.text.length == 0) && (_dataString.length == 0)) {
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"No data is unable to send！" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:okAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Are you sure？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (_messageId.length != 0) {
                [[AFNetworkReachabilityManager sharedManager] startMonitoring];
                [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
                    if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
                    {
                        NSString *webServiceStr = [NSString stringWithFormat:
                                                   @"<web:deletePostDetailData>\
                                                   <arg0>%@</arg0>\
                                                   <arg1>%@</arg1>\
                                                   </web:deletePostDetailData>",COMPANY,_messageId];
                        
                        NetWorkTools *tools = [NetWorkTools shareTools];
                        [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostDetailImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
                            [self.navigationController popViewControllerAnimated:YES];
                        }];
                    }else
                    {
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"There is no network" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                        alert.delegate = self;
                        [alert show];
                    }
                }];
            }
            
            
            if ([self.postDelegate respondsToSelector:@selector(postValuesWithTitleStr:detailStr:productNum:data:type:dataName:)]) {
                // 调用代理对象的刷新方法，代理对象去实现方法
                [self.postDelegate postValuesWithTitleStr:_titleTextFiled.text detailStr:_detailTextFiled.text productNum:_productTextFiled.text data:_dataString type:_dataType dataName:_dataName];
            }
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
//视频第一帧
- (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    return thumbnailImage;
}

//#pragma mark ————————— 压缩视频 —————————————
//- (void)compressVideo:(NSURL*)url {
//    NSLog(@"压缩");
//    //使用媒体工具(AVFoundation框架下的)
//    
//    //Asset 资源可以是图片音频视频
//    AVAsset *asset=[AVAsset assetWithURL:url];
//    
//    //设置压缩的格式
//    AVAssetExportSession *session=[AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetMediumQuality];//mediumquality:中等质量
//    
//    //设置导出路径
//    NSString *path=[NSTemporaryDirectory() stringByAppendingPathComponent:[self getVideoNameBaseCurrentTime]];
//    
//    //创建文件管理类导出失败,删除已经导出的
//    NSFileManager *manager=[[NSFileManager alloc]init];
//    
//    //删除已经存在的
//    [manager removeItemAtPath:path error:NULL];
//    
//    //设置到处路径
//    session.outputURL=[NSURL fileURLWithPath:path];
//    
//    //设置输出文件的类型
//    session.outputFileType=AVFileTypeQuickTimeMovie;
//    
//    //开辟子线程处理耗时操作
//    [session exportAsynchronouslyWithCompletionHandler:^{
//        
//        NSURL *url = [NSURL URLWithString:@"file:///private/var/mobile/Containers/Data/Application/0DA5B563-2142-4324-B717-64FD8AE05A0F/tmp/20170614103321.mov"];
//        NSLog(@"%@",url);
//        NSData *data = [NSData dataWithContentsOfURL:url];
//        
//        NSString *base64String = [data base64EncodedStringWithOptions:0];
//        _dataString = base64String;
//        NSLog(@"导出完成!路径:%@",_dataString);
//        
//    }];
//}
//
#pragma mark -------textField代理-------
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _titleTextFiled) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }else if (textField == _productTextFiled){
        [self share];
    
    }
    return YES;
}

#pragma mark ————————— 以当前时间合成视频名称 —————————————
- (NSString *)getNameBaseCurrentTime:(NSString *)type{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:type];
}




@end
